package com.itmayiedu.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.config.AlipayConfig;
import com.feign.OrderServiceFeign;
import com.itmayiedu.api.service.CallBackService;
import com.itmayiedu.base.BaseApiService;
import com.itmayiedu.base.ResponseBase;
import com.itmayiedu.constants.Constants;
import com.itmayiedu.dao.PaymentInfoDao;
import com.itmayiedu.entity.PaymentInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Author cht 【wonderfor@vip.qq.com】
 * @Date 2018/11/6
 */
@RestController
@Slf4j
public class CallBackServiceImpl extends BaseApiService implements CallBackService{

    @Autowired
    private OrderServiceFeign orderServiceFeign;

    @Autowired
    private PaymentInfoDao paymentInfoDao;

    @Override
    public ResponseBase synCallBack(@RequestParam Map<String, String> params) {
        //1.日志记录
        log.info("######支付宝同步通知synCallBack######开始,params:{}", params);
        //2.验签操作
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            log.info("######支付宝同步通知signVerified:{}######", signVerified);
            if (!signVerified) {
                return setResultError("验签失败");
            }
            //——请在这里编写您的程序（以下代码仅作参考）——
            //商户订单号
            String outTradeNo = params.get("out_trade_no");
            //支付宝交易号
            String tradeNo = params.get("trade_no");
            //付款金额
            String totalAmount = params.get("total_amount");
            JSONObject data = new JSONObject();
            data.put("outTradeNo", outTradeNo);
            data.put("tradeNo", tradeNo);
            data.put("totalAmount", totalAmount);
            return setResultSuccess(data);
        } catch (AlipayApiException e) {
            log.error("######支付宝同步通知出现异常,ERROR:{}",e);
            return setResultError("系统错误");
        }finally {
            log.info("######支付宝同步通知synCallBack######结束,params:{}", params);
        }
    }

    @Override
    @Transactional
    public String asyncCallBack(@RequestParam Map<String, String> params) {
        //1.日志记录
        log.info("######支付宝异步通知synCallBack######开始,params:{}", params);
        //2.验签操作
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            log.info("######支付宝异步通知signVerified:{}######", signVerified);
            if (!signVerified) {
                return Constants.PAY_FAIL;
            }
            //——请在这里编写您的程序（以下代码仅作参考）——
            //商户订单号
            String outTradeNo = params.get("out_trade_no");
            PaymentInfo paymentInfo = paymentInfoDao.getByOrderIdPayInfo(outTradeNo);
            if(paymentInfo == null) {
                return Constants.PAY_FAIL;
            }
            //支付宝重试机制为并行
            Integer state = paymentInfo.getState();
            if(state == 1) {
                return Constants.PAY_SUCCESS;
            }
            //支付宝交易号
            String tradeNo = params.get("trade_no");
            //付款金额
            //判断实际的付款金额与商品金额是否有一致
            String totalAmount = params.get("total_amount");
            //修改支付状态
            paymentInfo.setState(1);//标识为已支付
            paymentInfo.setPayMessage(params.toString());
            paymentInfo.setPlatformorderId(tradeNo);

            Integer result = paymentInfoDao.updatePayInfo(paymentInfo);
            if(result <= 0) {
                return Constants.PAY_FAIL;
            }
            //调用订单接口
            ResponseBase orderResult = orderServiceFeign.updateOrder(1l, tradeNo, outTradeNo);
            if(!orderResult.getRtnCode().equals(Constants.HTTP_RES_CODE_200)) {
                //回滚 手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
                return Constants.PAY_FAIL;
            }

            return Constants.PAY_SUCCESS;
        } catch (AlipayApiException e) {
            log.error("######支付宝异步通知出现异常,ERROR:{}",e);
            return Constants.PAY_FAIL;
        }finally {
            log.info("######支付宝异步通知synCallBack######结束,params:{}", params);
        }
    }
}
